package chooseCourseStrategy;


import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import po.chooseCoursePO.ChooseCoursePO;
import po.userPO.StudentPO;
import data.CourseData.CourseData;
import data.UserData.UserData;

public class Strategy implements ChooseCourseStrategy {
	private UserData userdata;
	private ArrayList<ChooseCoursePO> totalList;
	private ArrayList<ChooseCoursePO> resultList;
	private CourseData courseData;

	
	public Strategy(ArrayList<ChooseCoursePO> totalList){
		try {
			userdata=new UserData();
			courseData=new CourseData();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		this.totalList=totalList;
		resultList=new ArrayList<>();
		processSort();
	}
	
	
	@Override
	public void processSort(){
		while(!totalList.isEmpty()){
			ChooseCoursePO chooseCoursePO=totalList.get(0);
			int maxNum=courseData.find(chooseCoursePO.getCourseId()).getMaxStudent();
			ArrayList<ChooseCoursePO> oneCoursePOs=new ArrayList<>();
			for(ChooseCoursePO one:totalList){
				if (one.getCourseId().equals(chooseCoursePO.getCourseId())) {
					oneCoursePOs.add(one);
				}
			}
			int selectNum=oneCoursePOs.size();
			if (selectNum<=maxNum) {
				resultList.addAll(oneCoursePOs);
			}
			else {
				ArrayList<ChooseCoursePO> sortResult=sort(oneCoursePOs,maxNum);
				resultList.addAll(sortResult);
			}
			totalList.removeAll(oneCoursePOs);
		}
	}
	

	public ArrayList<ChooseCoursePO> sort(
			ArrayList<ChooseCoursePO> chooseCoursePOs,int num) {

		try {
			userdata = new UserData();
		} catch (RemoteException exception) {
			exception.printStackTrace();
		}
		
		Collections.sort(chooseCoursePOs, new Comparator<ChooseCoursePO>() {

			private int getPriority(ChooseCoursePO po) {
				StudentPO studentPO=(StudentPO)userdata.find(po.getStudentId());
				int value=0;
				if (studentPO.getTotalSelectedCredit()==0) {
					value=40/1;
				}
				else
					value = 40 / studentPO.getTotalSelectedCredit(); //TODO 
				return value;
			}

			@Override
			public int compare(ChooseCoursePO o1, ChooseCoursePO o2) {
				return getPriority(o1) - getPriority(o2);
			}

		});
		List<ChooseCoursePO > list=chooseCoursePOs.subList(0, num);
		ArrayList<ChooseCoursePO> result=new ArrayList<>();
		for(ChooseCoursePO chooseCoursePO:list){
			result.add(chooseCoursePO);
		}
		return result;
	}
	
	public ArrayList<ChooseCoursePO> getResult(){
		return resultList;
	}

}
